/**
 * Builder.Alyr.Net 配置同步工具
 * 版本: V4.2.3
 * 作者: Builder.Alyr.Net Team
 * 网站: https://gitee.com/Alyr_space/Builder.Alyr.Net
 * 
 * 这个工具用于同步项目中所有配置文件的数据
 */

const fs = require('fs');
const path = require('path');
const UnifiedConfigManager = require('./unified-config-manager');

class ConfigSync {
  constructor() {
    this.configManager = new UnifiedConfigManager();
    this.projectRoot = path.resolve(__dirname, '..');
  }

  /**
   * 执行全量配置同步
   */
  async syncAll() {
    try {
      console.log('🔄 开始执行全量配置同步...');
      
      // 加载当前配置
      await this.configManager.loadConfig();
      
      // 执行同步
      const results = await this.configManager.syncToAllFiles();
      
      // 分析结果
      const successResults = results.filter(r => r.success);
      const errorResults = results.filter(r => !r.success);
      
      // 输出结果
      console.log('\n✅ 配置同步完成！');
      console.log(`📊 同步统计: 成功 ${successResults.length} 个文件，失败 ${errorResults.length} 个文件`);
      
      if (successResults.length > 0) {
        console.log('\n✅ 成功同步的文件:');
        successResults.forEach(result => {
          console.log(`   - ${result.file}`);
        });
      }
      
      if (errorResults.length > 0) {
        console.log('\n❌ 同步失败的文件:');
        errorResults.forEach(error => {
          console.log(`   - ${error.file}: ${error.error}`);
        });
      }
      
      return { success: successResults, errors: errorResults };
    } catch (error) {
      console.error('❌ 配置同步失败:', error.message);
      throw error;
    }
  }

  /**
   * 同步特定文件
   */
  async syncFile(filePath) {
    try {
      console.log(`🔄 同步文件: ${filePath}`);
      
      await this.configManager.loadConfig();
      const result = await this.configManager.syncToFile(filePath);
      
      console.log(`✅ 文件同步完成: ${result.file}`);
      return result;
    } catch (error) {
      console.error(`❌ 文件同步失败: ${error.message}`);
      throw error;
    }
  }

  /**
   * 验证配置一致性
   */
  async validateConsistency() {
    try {
      console.log('🔍 验证配置一致性...');
      
      await this.configManager.loadConfig();
      const config = this.configManager.config;
      const issues = [];

      // 检查所有目标文件
      const targetFiles = this.configManager.targetFiles;
      
      for (const filePath of targetFiles) {
        // 处理相对路径，如果以../开头，则相对于config目录
        let fullPath;
        if (filePath.startsWith('../')) {
          fullPath = path.resolve(__dirname, filePath);
        } else {
          fullPath = path.resolve(this.projectRoot, filePath);
        }
        
        if (!fs.existsSync(fullPath)) {
          issues.push(`文件不存在: ${filePath}`);
          continue;
        }

        try {
          const content = fs.readFileSync(fullPath, 'utf8');
          
          // 检查版本号一致性
          const versionMatches = content.match(/v?(\d+\.\d+(?:\.\d+)?)/g);
          if (versionMatches) {
            const inconsistentVersions = versionMatches.filter(v => 
              !v.includes(config.project.version)
            );
            if (inconsistentVersions.length > 0) {
              issues.push(`${filePath}: 版本号不一致 ${inconsistentVersions.join(', ')}`);
            }
          }
          
          // 检查项目名称一致性
          if (content.includes('Builder.Alyr.Net') && 
              !content.includes(config.project.displayName)) {
            // 这里可以添加更详细的检查逻辑
          }
          
        } catch (error) {
          issues.push(`${filePath}: 读取文件失败 - ${error.message}`);
        }
      }

      if (issues.length === 0) {
        console.log('✅ 配置一致性验证通过！');
      } else {
        console.log('⚠️  发现配置不一致问题:');
        issues.forEach(issue => console.log(`   - ${issue}`));
      }

      return { consistent: issues.length === 0, issues };
    } catch (error) {
      console.error('❌ 配置一致性验证失败:', error.message);
      throw error;
    }
  }

  /**
   * 获取配置摘要
   */
  async getConfigSummary() {
    try {
      await this.configManager.loadConfig();
      return this.configManager.getConfigSummary();
    } catch (error) {
      console.error('❌ 获取配置摘要失败:', error.message);
      throw error;
    }
  }
}

// 如果直接运行此文件，执行同步
if (require.main === module) {
  const sync = new ConfigSync();
  
  const command = process.argv[2];
  
  switch (command) {
    case 'sync':
      sync.syncAll().catch(console.error);
      break;
    case 'validate':
      sync.validateConsistency().catch(console.error);
      break;
    case 'summary':
      sync.getConfigSummary().then(summary => {
        console.log('📋 配置摘要:');
        console.log(JSON.stringify(summary, null, 2));
      }).catch(console.error);
      break;
    default:
      console.log('用法:');
      console.log('  node config-sync.js sync     - 执行全量配置同步');
      console.log('  node config-sync.js validate - 验证配置一致性');
      console.log('  node config-sync.js summary  - 显示配置摘要');
  }
}

module.exports = ConfigSync;